<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="1200px" top="5vh">
    <el-scrollbar
      maxHeight="70vh"
      ref="scrollarRef"
      style="margin-right: -13px; padding-right: 13px"
    >
      <el-form
        :model="formData"
        ref="customerFormRef"
        :rules="customerModuleField.rules"
        vloading="formLoading"
        :inline="true"
        label-width="auto"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入名称" clearable />
        </el-form-item>
        <el-form-item label="简称" prop="shortName">
          <el-input v-model="formData.shortName" placeholder="请输入简称" clearable />
        </el-form-item>

        <el-form-item label="来源" prop="source">
          <el-select
            v-model="formData.source"
            :empty-values="[0]"
            :value-on-clear="0"
            clearable
            placeholder="请选择来源"
            filterable
          >
            <el-option
              v-for="item in customerModuleField.immutableFields.get('source')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="grade">
          <el-select
            v-model="formData.grade"
            :empty-values="[0]"
            :value-on-clear="0"
            clearable
            placeholder="请选择等级"
            filterable
          >
            <el-option
              v-for="item in customerModuleField.immutableFields.get('grade')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="阶段" prop="stage">
          <el-select
            v-model="formData.stage"
            :empty-values="[0]"
            :value-on-clear="0"
            clearable
            placeholder="请选择阶段"
            filterable
          >
            <el-option
              v-for="item in customerModuleField.immutableFields.get('stage')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select
            v-model="formData.state"
            :empty-values="[0]"
            :value-on-clear="0"
            clearable
            placeholder="请选择状态"
            filterable
          >
            <el-option
              v-for="item in customerModuleField.immutableFields.get('state')?.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="拥有人" prop="ownerId">
          <el-select v-model="formData.ownerId" placeholder="请输入拥有人">
            <el-option
              v-for="item in ownerUserList"
              :key="item.id"
              :label="item.nickname"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :data="deptList"
            :props="defaultProps"
            check-strictly
            node-key="id"
            placeholder="请选择所属部门"
          />
        </el-form-item>

        <el-form-item label="国家" prop="countryId">
          <el-select
            v-model="formData.countryId"
            filterable
            placeholder="请选择国家"
            @change="handleCountryChange"
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
          >
            <el-option
              v-for="item in countryList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="省" prop="provinceId">
          <el-select
            v-model="formData.provinceId"
            filterable
            placeholder="请选择省"
            @change="handlePrivinceChange"
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
          >
            <el-option
              v-for="item in provinceList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市" prop="cityId">
          <el-select
            v-model="formData.cityId"
            filterable
            placeholder="请选择市"
            @change="handleCityChange"
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
          >
            <el-option v-for="item in cityList" :key="item.id" :label="item.name" :value="item.id"
          /></el-select>
        </el-form-item>
        <el-form-item label="区" prop="districtId">
          <el-select
            v-model="formData.districtId"
            placeholder="请选择区"
            filterable
            clearable
            :empty-values="[0]"
            :value-on-clear="0"
          >
            <el-option
              v-for="item in districtList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="网址" prop="websites">
          <DynamicField v-model="formData.websites">
            <template #default="{ row }">
              <el-input v-model="row.website">{{ row.website }} clearable</el-input>
            </template>
          </DynamicField>
        </el-form-item>

        <el-row>
          <el-form-item label="图片">
            <UploadImgs height="70px" width="80px" v-model="imageData.images" />
          </el-form-item>
        </el-row>
      </el-form>
      <el-form
        :model="formData"
        ref="customerCustomFormRef"
        :rules="customerModuleField.rules"
        vloading="formLoading"
        :inline="true"
        label-width="auto"
      >
        <el-form-item
          v-for="(customerCustomField, index) in customerModuleField.customFields"
          :key="index"
          :label="customerCustomField.showName"
          :prop="customerCustomField.fieldName"
        >
          <el-input
            v-if="customerCustomField.options.length == 0"
            v-model="formData[customerCustomField.fieldName]"
            :placeholder="'请输入' + customerCustomField.showName"
            clearable
          />
          <el-select
            v-else
            :empty-values="['']"
            :value-on-clear="''"
            clearable
            :placeholder="'请输入' + customerCustomField.showName"
            v-model="formData[customerCustomField.fieldName]"
            allow-create
            filterable
            default-first-option
            @blur="(event) => handleCustomerCustomFieldBlur(customerCustomField.fieldName, event)"
            @change="
              (value) => handleCustomerCustomFieldChange(customerCustomField.fieldName, value)
            "
          >
            <el-option
              v-for="item in customerCustomField.options"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <transition-group name="card" tag="div">
        <el-card
          v-for="(contact, index) in formData.contacts"
          :key="cardKey[index]"
          style="margin-bottom: 15px; margin-top: 15px"
          v-show="contact.operateType != 'deleted'"
        >
          <el-collapse v-model="collapses[index]" style="border: none; transition: none">
            <el-collapse-item :name="collapses[index][0]" style="border: none; transition: none">
              <template #title>
                <div style="display: flex">
                  <div class="font-bold">{{ '联系人_' + (index + 1) }}</div>
                  <el-button
                    style="font-weight: bold; margin-left: 15px; margin-top: 12px"
                    :style="contact.isMain ? 'color: green' : 'color:black'"
                    size="small"
                    @click.stop.prevent="() => handleSetMasterContact(index)"
                  >
                    {{ contact.isMain ? '主' : '副' }}
                  </el-button>
                </div>
                <el-button style="margin-left: auto" link @click.stop.prevent="handleAddContact">
                  <Icon icon="ic:outline-add-circle-outline" :size="24" />
                </el-button>
                <el-button
                  v-if="!contact.isMain"
                  link
                  @click.stop.prevent="() => handleDeleteContact(index)"
                  style="margin-left: 0"
                >
                  <Icon icon="material-symbols-light:delete" :size="24" />
                </el-button>
              </template>
              <template #icon="{ isActive }">
                <Icon
                  :size="24"
                  :icon="isActive ? 'ic:round-keyboard-arrow-up' : 'ic:round-keyboard-arrow-down'"
                  class="el-collapse-item-arrow"
                />
              </template>
              <el-form
                :ref="(el) => setContactFormRef(el, index)"
                :model="contact"
                :inline="true"
                label-width="auto"
                :rules="contactModuleField.rules"
              >
                <el-form-item label="姓名" prop="name">
                  <el-input v-model="contact.name" placeholder="请输入姓名" clearable />
                </el-form-item>
                <el-form-item label="昵称" prop="nickName">
                  <el-input v-model="contact.nickName" placeholder="请输入昵称" clearable />
                </el-form-item>
                <el-form-item label="决策角色" prop="decisionRole">
                  <el-select
                    v-model="contact.decisionRole"
                    placeholder="请选择决策角色"
                    clearable
                    :empty-values="[0]"
                    :value-on-clear="0"
                    filterable
                  >
                    <el-option
                      v-for="item in contactModuleField.immutableFields.get('decisionRole')
                        ?.options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="职位" prop="position">
                  <el-input v-model="contact.position" placeholder="请输入职位" clearable />
                </el-form-item>
                <el-form-item label="工作状态" prop="workState">
                  <el-select
                    v-model="contact.workState"
                    placeholder="请选择工作状态"
                    clearable
                    :empty-values="[0]"
                    :value-on-clear="0"
                    filterable
                  >
                    <el-option
                      v-for="item in contactModuleField.immutableFields.get('workState')?.options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="性别" prop="sex">
                  <el-select
                    v-model="contact.sex"
                    :empty-values="[0]"
                    :value-on-clear="0"
                    placeholder="请选择性别"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in contactModuleField.immutableFields.get('sex')?.options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
                <el-row>
                  <el-form-item label="电话" prop="phones">
                    <DynamicField v-model="contact.phones">
                      <template #default="{ row }">
                        <el-input v-model="row.phoneNo" clearable>{{ row.phoneNo }} </el-input>
                      </template>
                    </DynamicField>
                  </el-form-item>
                </el-row>
                <el-row>
                  <el-form-item label="邮箱" prop="mails">
                    <DynamicField v-model="contact.mails">
                      <template #default="{ row }">
                        <el-input v-model="row.mailAddress" clearable
                          >{{ row.mailAddress }}
                        </el-input>
                      </template>
                    </DynamicField>
                  </el-form-item>
                </el-row>

                <el-row>
                  <el-form-item label="社交媒体" prop="socialMedias">
                    <DynamicField v-model="contact.socialMedias">
                      <template #default="{ row }">
                        <el-select
                          v-model="row.socialType"
                          placeholder="请选择类型"
                          clearable
                          :empty-values="[0, undefined]"
                          :value-on-clear="0"
                          style="width: 120px"
                          class="mr-2"
                        >
                          <el-option
                            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_SOCIAL_MEDIA_TYPE)"
                            :key="dict.value"
                            :label="dict.label"
                            :value="dict.value"
                          />
                        </el-select>
                        <el-input v-model="row.socialAccount">{{ row.socialAccount }} </el-input>
                      </template>
                    </DynamicField>
                  </el-form-item>
                </el-row>
                <el-form-item label="地址" prop="address">
                  <el-input
                    v-model="contact.address"
                    placeholder="请输入地址"
                    clearable
                    type="textarea"
                    style="width: 280px"
                  />
                </el-form-item>

                <el-form-item label="名片">
                  <UploadImgs height="70px" width="80px" v-model="imageData.contacts[index]" />
                </el-form-item>
              </el-form>
              <el-form
                :model="contact"
                :ref="(el) => setContactCustomFormRef(el, index)"
                :rules="contactModuleField.rules"
                vloading="formLoading"
                :inline="true"
                label-width="auto"
              >
                <el-form-item
                  v-for="(contactCustomField, customIndex) in contactModuleField.customFields"
                  :key="customIndex"
                  :label="contactCustomField.showName"
                  :prop="contactCustomField.fieldName"
                >
                  <el-input
                    v-if="contactCustomField.options.length == 0"
                    v-model="contact[contactCustomField.fieldName]"
                    :placeholder="'请输入' + contactCustomField.showName"
                    clearable
                  />
                  <el-select
                    v-else
                    :empty-values="['']"
                    :value-on-clear="''"
                    clearable
                    :placeholder="'请输入' + contactCustomField.showName"
                    v-model="contact[contactCustomField.fieldName]"
                    allow-create
                    filterable
                    default-first-option
                    @blur="
                      (event) =>
                        handleContactCustomFieldBlur(index, contactCustomField.fieldName, event)
                    "
                    @change="
                      (value) =>
                        handleContactCustomFieldChange(index, contactCustomField.fieldName, value)
                    "
                  >
                    <el-option
                      v-for="item in contactCustomField.options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </el-collapse-item>
          </el-collapse>
        </el-card>
      </transition-group>
    </el-scrollbar>
    <template #footer>
      <el-button type="primary" :disabled="formLoading" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup name="CustomerEdit" lang="ts">
import type { UploadUserFile, FormInstance } from 'element-plus'

import { CustomerInfo as CustomerInfoModel } from '@/model/customer/info/CustomerInfo'
import { CustomerImage as CustomerImageModel } from '@/model/customer/info/CustomerImage'
import { CustomerWebsite as CustomerWebsiteModel } from '@/model/customer/info/CustomerWebsite'
import { CustomerContact as CustomerContactModel } from '@/model/customer/contact/CustomerContact'
import { CustomerContactBusinessCard as CustomerContactBusinessCardModel } from '@/model/customer/contact/CustomerContactBusinessCard'
import { CustomerContactMail as CustomerContactMailModel } from '@/model/customer/contact/CustomerContactMail'
import { CustomerContactPhone as CustomerContactPhoneModel } from '@/model/customer/contact/CustomerContactPhone'
import { CustomerContactSocialMedia as CustomerContactSocialMediaModel } from '@/model/customer/contact/CustomerContactSocialMedia'

import { DynamicField } from '@/components/DynamicField/index'
import { UploadImgs } from '@/components/UploadFile/index'

import * as DeptApi from '@/api/system/dept/dept'
import * as AreaApi from '@/api/infra/data/area'
import * as CustomerApi from '@/api/customer/customer'
import * as UserApi from '@/api/system/user/user'

import { useUserStore } from '@/store/modules/user'
import { SettingBusinessModuleEnum } from '@/utils/constants'
import { defaultProps, handleTree } from '@/utils/tree'
import { cloneDeep } from '@pureadmin/utils'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { getBussinessModule } from '@/views/setting/businessField/BusinessFieldUtil'

interface imageModel extends UploadUserFile {
  id: number | undefined
}

interface imageDataModel {
  images: imageModel[]
  contacts: imageModel[][]
}

interface CustomerContactMailEditModel extends CustomerContactMailModel {
  operateType: string
}

interface CustomerContactPhoneEditModel extends CustomerContactPhoneModel {
  operateType: string
}

interface CustomerContactSocialMediaEditModel extends CustomerContactSocialMediaModel {
  operateType: string
}

interface CustomerContactEditModel extends CustomerContactModel {
  operateType: string
  businessCards: CustomerContactBusinessCardModel[]
  mails: CustomerContactMailEditModel[]
  phones: CustomerContactPhoneEditModel[]
  socialMedias: CustomerContactSocialMediaEditModel[]
}

interface CustomerWebsiteEditModel extends CustomerWebsiteModel {
  operateType: string
}
interface CustomerInfoEditModel extends CustomerInfoModel {
  images: CustomerImageModel[]
  websites: CustomerWebsiteEditModel[]
  contacts: CustomerContactEditModel[]
}

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const userStore = useUserStore()

const emptyContact = {
  id: undefined,
  name: '',
  sex: 0,
  address: '',
  position: '',
  decisionRole: 0,
  workState: 0,
  customField1: '',
  customField2: '',
  customField3: '',
  customField4: '',
  customField5: '',
  customField6: '',
  customField7: '',
  customField8: '',
  customField9: '',
  customField10: '',
  customerId: undefined,
  operateType: 'new',
  businessCards: [],
  mails: [],
  phones: [],
  socialMedias: []
}
const emptyFormData = {
  id: undefined,
  customerNo: '',
  name: '',
  mainImageUrl: '',
  source: 0,
  grade: 0,
  stage: 0,
  state: 0,
  ownerId: userStore.getUser.id,
  countryId: 0,
  provinceId: 0,
  cityId: 0,
  districtId: 0,
  address: '',
  deptId: userStore.getUser.deptId,
  customField1: '',
  customField2: '',
  customField3: '',
  customField4: '',
  customField5: '',
  customField6: '',
  customField7: '',
  customField8: '',
  customField9: '',
  customField10: '',
  customField11: '',
  customField12: '',
  customField13: '',
  customField14: '',
  customField15: '',
  customField16: '',
  customField17: '',
  customField18: '',
  customField19: '',
  customField20: '',
  mainContactId: undefined,
  isRecycle: false,
  images: [],
  websites: [],
  contacts: [{ ...cloneDeep(emptyContact), isMain: true }]
}
const customerDefaultRule = {
  name: [{ required: true, message: '请输入名称', trigger: 'change' }],
  ownerId: [{ required: true, message: '请选择所属人', trigger: 'change' }],
  deptId: [{ required: true, message: '请选择所属部门', trigger: 'change' }]
}
const contactDefaultRule = {
  name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
  mails: [{ type: 'array', required: true, message: '请输入邮箱', trigger: 'change' }]
}

const dialogTitle = ref('新增客户')
const dialogVisible = ref(false)
const customerFormRef = ref()
const customerCustomFormRef = ref()
const contactFormRef = ref<FormInstance[]>([])
const contactCustomFormRef = ref<FormInstance[]>([])
const formLoading = ref(false)
const formData = ref<CustomerInfoEditModel>(cloneDeep(emptyFormData))
const imageData = ref<imageDataModel>({ images: [], contacts: [[]] })

const countryList = ref()
const provinceList = ref()
const cityList = ref()
const districtList = ref()
const ownerUserList = ref<UserApi.UserVO[]>([]) // 用户列表
const deptList = ref<Tree[]>([]) // 树形结构
const scrollarRef = ref()
const collapses = ref([[0]])
const cardCount = ref(1)
const cardKey = ref([0])
let deletedContacts = [] as CustomerContactEditModel[]
const customerModuleField = ref()
const contactModuleField = ref()

/** 打开弹窗 */
const open = async (id) => {
  reset()
  await dataInit()
  await getCustomerInfo(id)
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

const reset = () => {
  collapses.value = [[0]]
  cardCount.value = 1
  cardKey.value = [0]
  deletedContacts = []

  formData.value = cloneDeep(emptyFormData)
}

const dataInit = async () => {
  // 加载部门树
  deptList.value = handleTree(await DeptApi.listAllSimple())
  // 获得用户列表
  ownerUserList.value = await UserApi.getOwnerUser()
  // 加载业务字段
  customerModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER)
  customerModuleField.value.rules = {
    ...cloneDeep(customerDefaultRule),
    ...customerModuleField.value.rules
  }

  contactModuleField.value = await getBussinessModule(SettingBusinessModuleEnum.CUSTOMER_CONTACT)
  contactModuleField.value.rules = {
    ...cloneDeep(contactDefaultRule),
    ...contactModuleField.value.rules
  }

  countryList.value = await AreaApi.countryList()

  imageData.value = { images: [], contacts: [[]] }
}

const getCustomerInfo = async (id) => {
  if (id == 0) return
  formData.value = await CustomerApi.singleGetDetail(id)
  if (formData.value.provinceId != 0) {
    provinceList.value = await AreaApi.provinceListByCountryId(formData.value.countryId)
  }
  if (formData.value.cityId != 0) {
    cityList.value = await AreaApi.cityListByProvinceId(formData.value.provinceId)
  }
  if (formData.value.districtId != 0) {
    districtList.value = await AreaApi.districtListByCityId(formData.value.cityId)
  }

  initImageData()
  initCollapses()
}

const initImageData = () => {
  formData.value.images.forEach((image) => {
    imageData.value.images.push({
      id: image.id,
      url: image.url,
      name: image.url
    })
  })
  let contactIndex = 0

  formData.value.contacts.forEach((contact) => {
    imageData.value.contacts[contactIndex] ??= []
    contact.businessCards.forEach((card) => {
      imageData.value.contacts[contactIndex].push({
        id: card.id,
        url: card.url,
        name: card.url
      })
    })
    contactIndex++
  })
}

const initCollapses = () => {
  const count = formData.value.contacts.length - 1
  for (let index = 0; index < count; index++) {
    cardKey.value.push(cardCount.value)
    collapses.value.push([cardCount.value])
    imageData.value.contacts.push([])
    cardCount.value = cardCount.value + 1
  }
}

const handleCustomerCustomFieldBlur = (fieldName, event) => {
  if (event.target.value != '') formData.value[fieldName] = event.target.value
}

const handleCustomerCustomFieldChange = (fieldName, value) => {
  formData.value[fieldName] = value
}

const handleContactCustomFieldBlur = (index, fieldName, event) => {
  if (event.target.value != '') formData.value.contacts[index][fieldName] = event.target.value
}

const handleContactCustomFieldChange = (index, fieldName, value) => {
  formData.value.contacts[index][fieldName] = value
}

const handleCountryChange = async (id) => {
  if (id != undefined || id != 0) provinceList.value = await AreaApi.provinceListByCountryId(id)
  formData.value.provinceId = 0
  formData.value.cityId = 0
  formData.value.districtId = 0
  cityList.value = []
  districtList.value = []
}

const handlePrivinceChange = async (id) => {
  if (id != undefined || id != 0) cityList.value = await AreaApi.cityListByProvinceId(id)
  formData.value.cityId = 0
  formData.value.districtId = 0
  districtList.value = []
}

const handleCityChange = async (id) => {
  if (id != undefined || id != 0) districtList.value = await AreaApi.districtListByCityId(id)
}

const handleAddContact = async () => {
  cardKey.value.push(cardCount.value)
  collapses.value.push([cardCount.value])
  imageData.value.contacts.push([])
  formData.value.contacts.push({
    ...cloneDeep(emptyContact),
    isMain: false,
    customerId: formData.value.id
  })
  cardCount.value = cardCount.value + 1
  await nextTick()
  scrollarRef.value.scrollTo({
    top: scrollarRef.value.wrapRef.offsetHeight,
    behavior: 'smooth'
  })
}

const handleDeleteContact = (deleteIndex) => {
  if (formData.value.contacts[deleteIndex].isMain) {
    message.error('主联系人不能删除')
    return
  }
  if (formData.value.id != undefined) {
    formData.value.contacts[deleteIndex].operateType = 'delete'
    deletedContacts.push(cloneDeep(formData.value.contacts[deleteIndex]))
  }
  cardKey.value.splice(deleteIndex, 1)
  collapses.value.splice(deleteIndex, 1)
  formData.value.contacts.splice(deleteIndex, 1)
  imageData.value.contacts.splice(deleteIndex, 1)
}

const handleSetMasterContact = (index) => {
  if (formData.value.contacts[index].isMain) {
    if (formData.value.contacts.length == 1) {
      message.error('客户必须至少有一个主联系人')
      return
    }
    let isSetMaster = false
    let currentIndex = 0
    formData.value.contacts.forEach((contact) => {
      if (!contact.isMain && currentIndex != index && !isSetMaster) {
        isSetMaster = true
        contact.isMain = true
      }
      currentIndex++
    })
    formData.value.contacts[index].isMain = false
  } else {
    formData.value.contacts.forEach((contact) => {
      if (contact.isMain) {
        contact.isMain = false
      }
    })
    formData.value.contacts[index].isMain = true
  }
}

const setContactFormRef = (el, index) => {
  if (el) {
    // 确保不会重复添加相同的 ref
    if (!contactFormRef.value[index]) {
      contactFormRef.value[index] = el
    }
  }
}

const setContactCustomFormRef = (el, index) => {
  if (el) {
    // 确保不会重复添加相同的 ref
    if (!contactCustomFormRef.value[index]) {
      contactCustomFormRef.value[index] = el
    }
  }
}

const emit = defineEmits(['success'])
/** 提交表单 */
const submitForm = async () => {
  // 校验
  if (!(await validateForm())) return

  // 将图片合并到formData
  mergeImageData()

  // 将删除的联系人合并到formData
  let customerInfo = cloneDeep(formData.value)
  customerInfo.contacts = formData.value.contacts.concat(deletedContacts)
  try {
    if (formData.value.id == undefined) {
      await CustomerApi.create(customerInfo)
      message.success(t('common.createSuccess'))
    } else {
      await CustomerApi.update(customerInfo)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
  }
}

const validateForm = async () => {
  try {
    if (!customerFormRef) return false
    await customerFormRef.value.validate()

    if (!customerCustomFormRef) return
    await customerCustomFormRef.value.validate()

    await Promise.all(contactFormRef.value.map((formRef) => formRef.validate()))
    await Promise.all(contactCustomFormRef.value.map((formRef) => formRef.validate()))
    return true
  } catch (error: object) {
    if (typeof error === 'object') {
      const keys = Object.keys(error)
      message.error(error[keys[0]][0].message)
    }

    return false
  }
}

const mergeImageData = () => {
  formData.value.images = []
  imageData.value.images.forEach((item) => {
    if (item.url != undefined)
      formData.value.images.push({
        id: item.id,
        customerId: formData.value.id,
        url: item.url
      })
  })
  let currentIndex = 0
  imageData.value.contacts.forEach((contact) => {
    if (formData.value.contacts[currentIndex] == undefined) return
    formData.value.contacts[currentIndex].businessCards = []
    if (contact != undefined && contact.length > 0) {
      contact.forEach((item) => {
        if (item.url != undefined)
          formData.value.contacts[currentIndex].businessCards.push({
            id: item.id,
            contactId: formData.value.contacts[currentIndex].id,
            url: item.url
          })
      })
    }
    currentIndex++
  })
}
</script>
<style lang="scss" scoped>
:deep(.el-collapse-item__header) {
  pointer-events: none;
}

:deep(.el-collapse-item__header button) {
  pointer-events: auto;
}

:deep(.el-collapse-item-arrow) {
  pointer-events: auto;
}
:deep(.el-collapse-item__wrap) {
  border: none;
}

:deep(.scroll-wrap) {
  height: 100%;
  margin-right: -17px;
  padding-right: 17px;
}

/* 定义 card 过渡 */
:deep(.card-enter-active) {
  transition: 0.8s ease;
}

:deep(.card-leave-active) {
  transition: 0.8s ease;
}
:deep(.card-entry-to) {
  opacity: 0;
  transform: translateY(30px);
}

:deep(.card-leave-to) {
  opacity: 0;
  transform: translateY(30px);
}

:deep(el-scrollbar) {
  transition: none !important;
}
</style>
